package org.xilin.service

import org.xilin.*
import javax.servlet.http.HttpSession
import org.springframework.web.context.request.RequestContextHolder

class ClassRegisterService {


    static scope = "session"

    def grailsApplication

    def authenticateService

    static transactional = true

    private HttpSession getSession() {
        return RequestContextHolder.currentRequestAttributes().getSession()
    }

    def getUserFamily() {
        def user = authenticateService.userDomain()
        def userFamily =  Family.findByUserId(user.username)
    }

   
    def getMyStudents() {
        def myFamily = getUserFamily()
        myFamily?.students?.toList().sort()
    }

    def addClass(courseInstance, studentInstance) {
        def myCourses = studentInstance?.classes.collect{it.course}
        def retVal = true
        def timeConflict = false
        myCourses.each { it->
            if(courseInstance.startTime == it.startTime) {
                timeConflict = true
            }
            if(courseInstance.endTime > it.startTime && courseInstance.endTime < it.endTime) {
                timeConflict = true
            }
        }
        if(timeConflict) {
            retVal = false       // time confllict
        } else {
            courseInstance.regCapacity++
            if( courseInstance.book){
                courseInstance.book.reserve++
                courseInstance.book.save(flash:true)
            }
            courseInstance.save(flush:true)
            def c = TheClass.link(courseInstance, studentInstance)
//        studentInstance.save(flush: true)
//            setStudent(studentInstance)
        }
        return retVal
    }

    def dropClass(studentInstance, courseInstance) {
        def student = TheClass.unlink(courseInstance, studentInstance)
        courseInstance.regCapacity--
        courseInstance.save(flush:true)
//        studentInstance.save(flush: true)
    }

    def getListSemester(domainObj) {
        def list = domainObj.findAllBySemester(session.activeSemester)
        return list
    }
}
